/**
 * Created by leezhihua on 2018/7/20
 * @flow
 * */

'use strict';

import React, {Component} from 'react';


let Digit = {
	/**
	 * 每3个数用逗号隔开
	 * @param  {Number}  num 需要转化的数值
	 * @return {String}
	 */

	toCutNumber(num = 0) {
		num = parseFloat(num);
		if (isNaN(num)) {
			num = 0;
		}
		let sReturn = num.toString();

		if (sReturn.indexOf('.') > -1) {
			let intNum = sReturn.split('.')[0];
			let dobNum = sReturn.split('.')[1];
			if (intNum.length >= 4) {
				sReturn = handleNum(intNum) + '.' + dobNum;
			}
		} else {
			sReturn = handleNum(sReturn);
		}

		function handleNum(intNum) {
			let mod = intNum.length % 3;
			let output = (mod === 0 ? '' : (intNum.substring(0, mod)));
			for (let i = 0, len = Math.floor(intNum.length / 3); i < len; i++) {
				if ((mod === 0) && (i === 0)) {
					output += intNum.substring(0, 3);
				}
				else {
					output += ',' + intNum.substring(mod + 3 * i, mod + 3 * i + 3);
				}
			}
			return output;
		}

		return sReturn;
	},

	/**
	 * 四舍五入保留小数
	 * @param  {Number}  num            需要转化的数值
	 * @param  {Integer}  cutNum        保留的小数位数
	 * @param  {Boolean} isRemoveZero   是否移除末尾的0，默认不需要
	 * @param  {Boolean} isCut          是否没3个数用逗号隔开，默认不需要（仅针对整数部分加逗号）
	 * @return {Number}
	 */

	toFixedNumber(num, cutNum, isRemoveZero, isCut) {
		let sReturn = '0';
		num = parseFloat(num);
		if (isNaN(num)) {
			num = 0;
		}
		cutNum = cutNum || 0;
		if (num.toString() === "NaN") {
			num = 0;
		} else {
			num = num.toFixed(cutNum);
		}

		sReturn = num.toString();
		if (isRemoveZero) {
			// console.log(sReturn);
			// console.log(typeof sReturn);
			while (sReturn.indexOf('.') > -1 && sReturn.endsWith('0')) {
				sReturn = sReturn.substr(0, sReturn.length - 1);
			}
			if (sReturn.endsWith(".")) {
				sReturn = sReturn.substring(0, sReturn.length - 1);
			}
		}
		if (isCut) {
			sReturn = toCutNum(sReturn)
		}
		return sReturn;
	},

};

export default Digit;